package com.webbuilder.utils;

import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.Date;  
import java.util.List; 


public class VideoUtil {

   /** 
     *  
     * 避免文件重名，在文件尾部加唯一标识，主要是以获取当前时间，以字符串格式hhmmssSSSSSS 
     */ 
	
    public static String transform(Date date) {  
        SimpleDateFormat sdFormat = new SimpleDateFormat("hhmmssSSSSSS");  
        String myTime = sdFormat.format(date);  
        return myTime;  
    }
	
	/** 
     * 生成图片 参数String newfilename, String newimg 
     * ffmpegPath  ffmpeg所在的路径
     * imgPath   转换后视频保存的地方
     */ 
    
    public static String processImg(String str,String ffmpegPath,String is_chang) {  
        List<String> commend = new java.util.ArrayList<String>();  
        //commend.add("\"e:\\ffmpeg1\\ffmpeg\"");  
        commend.add("\"" + ffmpegPath + "\"");  
        commend.add("-i");  
        commend.add("\"" + str + "\"");  
        commend.add("-y");  
        commend.add("-f");  
        commend.add("image2");  
        commend.add("-ss");  
        commend.add("5");  
        commend.add("-t");  
        commend.add("0.001");  
        commend.add("-s");  
        commend.add("320x240");  
        commend.add("\""+ str.substring(0, str.lastIndexOf(".")) + ".jpg\"");  
        try {  
            ProcessBuilder builder = new ProcessBuilder();  
            builder.command(commend);  
            builder.start();  
            /*
            str=StringUtil.replace(str, "/", "\\");
            deleteFile(str); */
        } catch (Exception e) {  
            e.printStackTrace();  
            return "";  
        }  
        return str.substring(0, str.lastIndexOf("."))+".jpg";  
    }
    
  /**
   * 删除文件  
   * 
   */
    
    public static void deleteFile(String str) {  
        File file = new File(str);  
        file.delete();  
    }  
  
    /** 
     * ffmpeg不能转换的格式要先转换成avi的格式，才转化为flv格式，doWaitFor方法保证，原视频完全转化为avi后， 
     * 才转化成flv，避免avi,flv同时转换出错 
     */  
    public static int doWaitFor(Process p)  
  
    {  
        InputStream in = null;  
        InputStream err = null;  
        int exitValue = -1; // returned to caller when p is finished  
        try {  
            System.out.println("comeing");  
            in = p.getInputStream();  
            err = p.getErrorStream();  
            boolean finished = false; // Set to true when p is finished  
  
            while (!finished) {  
                try {  
                    while (in.available() > 0) {  
                        // Print the output of our system call  
                        Character c = new Character((char) in.read());  
                        System.out.print(c);  
                    }  
                    while (err.available() > 0) {  
                        // Print the output of our system call  
                        Character c = new Character((char) err.read());  
                        System.out.print(c);  
                    }  
  
                    // Ask the process for its exitValue. If the process  
                    // is not finished, an IllegalThreadStateException  
                    // is thrown. If it is finished, we fall through and  
                    // the variable finished is set to true.  
                    exitValue = p.exitValue();  
                    finished = true;  
  
                } catch (IllegalThreadStateException e) {  
                    // Process is not finished yet;  
                    // Sleep a little to save on CPU cycles  
                    Thread.currentThread().sleep(500);  
                }  
            }  
        } catch (Exception e) {  
            // unexpected exception! print it out for debugging...  
            System.err.println("doWaitFor();: unexpected exception - "  
                    + e.getMessage());  
        } finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
  
            } catch (IOException e) {  
                System.out.println(e.getMessage());  
            }  
            if (err != null) {  
                try {  
                    err.close();  
                } catch (IOException e) {  
                    System.out.println(e.getMessage());  
                }  
            }  
        }  
        // return completion status to caller  
        return exitValue;  
    }  
	
	
	
	/** 
     * ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等） 
     * ffmpegPath  ffmpeg所在的路径
     * outPutPath   转换后视频保存的地方
     * 
     */  
   
    public static String processFLV(String str,String ffmpegPath,String is_chang) {
        List<String> commend = new java.util.ArrayList<String>();  
        //commend.add("\"e:\\ffmpeg1\\ffmpeg\"");  
        commend.add("\"" + ffmpegPath + "\"");  
        commend.add("-i");  
        commend.add("\"" + str + "\"");  
        commend.add("-ab");  
        commend.add("64"); 
        commend.add("-ac");  
        commend.add("2");  
        commend.add("-ar");  
        commend.add("22050");  
        commend.add("-b");  
        commend.add("230");  
        commend.add("-r");  
        commend.add("29.97");  
        commend.add("-y");  
        String file = str.substring(0,  
                str.lastIndexOf("."));  
        //String fileName = "e:\\output\\" + file + ".flv";  
        String fileName = file + ".flv";  
        commend.add("\"" + fileName + "\"");  
        String imgStr="";
        try {  
            ProcessBuilder builder = new ProcessBuilder();  
            builder.command(commend);  
            Process p = builder.start();  
            int exitValue = doWaitFor(p);  
            if (exitValue != -1) {  
                //fileNum++;  
            }  
             imgStr=processImg(fileName,ffmpegPath,is_chang); 
            
        } catch (Exception e) {  
            System.out.println("*********转换为FLV格式出错*********");  
            // e.printStackTrace();  
            //return false;  
        }  
        /*
        if(is_chang=="1"){
        	str=StringUtil.replace(str, "/", "\\");
            deleteFile(str); 
        	
           
        }*/
       
        
        return imgStr;
    }  
	
	
	/** 
     * 对ffmpeg无法解析的文件格式(wmv9，rm，rmvb等), 可以先用别的工具（mencoder）转换为avi(ffmpeg能解析的)格式. 
     * mencoderPath  mencoder所在的路径
     * outPutPath   转换后视频保存的地方
     * ffmpegPath   ffmpeg所在的路径
     */  
    public static String processAVI(String str,String mencoderPath,String ffmpegPath) {         
            List<String> commend = new java.util.ArrayList<String>();  
            //commend.add("\"e:\\ffmpeg1\\mencoder\""); 
            commend.add("\"" + mencoderPath + "\""); 
            commend.add("\"" + str + "\"");  
            commend.add("-oac");  
            commend.add("mp3lame");  
            commend.add("-lameopts");  
            commend.add("preset=64");  
            commend.add("-ovc");  
            commend.add("xvid");  
            commend.add("-xvidencopts");  
            commend.add("bitrate=600");  
            commend.add("-of");  
            commend.add("avi");  
            commend.add("-o");  
            String imag="";
            String file = str.substring(0,  
                    str.lastIndexOf("."));  
            //file = (file + transform(new Date())).trim();             
            //commend.add("\"e:\\System\\" + file + ".avi\""); // 最后输出出来的avi，尽量不要出现二义性，否则会覆盖掉原有的视频  
            commend.add("\""+file + ".avi\"");
            
            try {  
                ProcessBuilder builder = new ProcessBuilder();  
                builder.command(commend);  
                Process p = builder.start();  
                int exitValue = doWaitFor(p); 
                  
                if (exitValue != -1) {  
                	System.out.println("********avi********");
                	imag= processFLV(file + ".avi",ffmpegPath,"1");  
                	//finish.add(str); 
                }  
                
            } catch (Exception e) {  
                // e.printStackTrace();  
                System.out.println("********avi转换出错********");  
            }  
            return imag;
          
        //path2.removeAll(finish);  
    } 
    
    /** 
     * 核心处理函数 
     */  
    public static String process(String str,String mencoderPath,String ffmpegPath) { 
       String imag="";
    	if (str.matches(".+\\.(avi|wmv|mkv|asx|swf|asf|vob|mpg|mp4|mov|flv)$")) {  
    		imag= processFLV(str,ffmpegPath,"0");
            } else {  
            	imag=  processAVI(str,mencoderPath,ffmpegPath);  
            }  	
          return imag;
    }  
	
}
